<template>
  <!-- 商品橱窗对话框 -->
  <div class="shop-window">
    <el-dialog
      title="商品橱窗"
      :visible.sync="isShopWindow"
      width="80%"
      :before-close="cancel">
      <div class="shop-window-content">
        <el-row class="card-content">
          <!--    搜索-->
          <el-col :span="24" class="search-wrapper">
            <search :search-items="searchItems" @on-search="searchBySearchItem" v-if="isFinish"></search>
          </el-col>
          <!--    按钮和分页-->
          <el-col :span="24" class="btn-page-wrapper">
            <el-button type="success" @click="addGoods" :disabled="disabled">添加商品</el-button>
          </el-col>
          <!--    表格-->
          <el-col :span="24" class="data">
            <el-table :data="data" stripe>
              <el-table-column prop="title" label="商品名称" align="center"></el-table-column>
              <el-table-column prop="type" label="类型" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.type=='link'">外部商品</span>
                  <span v-else>SAAS商城商品</span>
                </template>
              </el-table-column>
              <el-table-column prop="picture" label="图片" align="center">
                <template slot-scope="scope">
                  <img :src="`https://tencentyun-ms-1312352800.cos.ap-guangzhou.myqcloud.com/${scope.row.thumbnail}`" style="width:50px;height:50px;"/>
                </template>
              </el-table-column>
              <el-table-column prop="specifications" label="规格" align="center"></el-table-column>
              <el-table-column prop="price" label="价格(￥)" align="center"></el-table-column>
              <el-table-column prop="link" label="商品外部链接" align="center"></el-table-column>
              <el-table-column prop="state" label="状态" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.sellable">已上架</span>
                  <span v-else>已下架</span>
                </template>
              </el-table-column>
              <el-table-column prop="operation" label="操作" align="center">
                <template slot-scope="scope">
                  <el-button @click.stop="takeDown(scope.row.position)" type="text" v-if="scope.row.sellable">下架</el-button>
                  <el-button @click.stop="shelves(scope.row.position)" type="text" v-else>上架</el-button>
                  <el-button @click.stop="down(scope.row.position)" v-if="scope.row.position != total && !disabled" type="text">下移</el-button>
                  <el-button @click.stop="up(scope.row.position)" v-if="scope.row.position != 1 && !disabled" type="text">上移</el-button>
                  <el-button @click.stop="remove(scope.row.position)" type="text" style="color:red;">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pager-group">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page"
                :page-sizes="[5, 10, 15, 20]"
                :page-size="pageSize"
                layout="total, sizes, jumper, prev, next"
                :total="total"
              ></el-pagination>
            </div>
          </el-col>
        </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="submit" :disabled="disabledSubmit">确认</el-button>
        <el-button @click="cancel">取消</el-button>
      </span>
    </el-dialog>
    <add @close="closeAdd" :id="id" :is-add="isAdd"></add>
  </div>
</template>

<script>
import Search from '@/framework/components/search'
import Add from './add'
import {findByVideo,save,countByVideo,batchDelete,batchReverse} from "@/project/service/product";

export default {
  name:'shopWindow',
  mixins: [
    // PageMixin,
  ],
  props: {
    isShopWindow:{
      type: Boolean,
      default: () => {
        return false
      }
    },
    id:{
      type: String,
      default: () => {
        return ''
      }
    },
  },
  data() {
    return {
      searchItems: [
        {name: '商品名称', key: 'title', type: 'string'},
        {
          name: '类型', key: 'type', type: 'select',
          displayValue: ['SAAS商城商品', '外部商品'],
          value:{0:'saas', 1:'link'}
        }
      ],
      page:1,
      pageSize:5,
      total:0,
      data: this.$store.state.addProductList.slice(0) || [],
      allProductList: [],//存储全部添加商品的列表
      isAdd: false,//是否添加商品
      // isFirst: true,//是否未进行条件搜索
      disabled: false,//禁用添加按钮
      isFinish: false,
      originalListLength: 0,//原有列表长度，编辑视频上传新商品时用来删除掉原有商品
      originalIdList: [],//视频原有商品的id列表
      disabledSubmit:false,//禁用确定按钮
    }
  },
  components:{ Search, Add },
  watch:{
    isShopWindow(val){
      if(val){
        this.disabledSubmit = false
        this.isFinish = true
        //编辑视频
        if(this.id){
          this.findProduct(this.id)
          // console.log(this.allProductList)
        }
        // console.log(this.id)
        this.listUpdate()
        // 备份商品列表数据
        this.$store.commit('saveOldProductList',this.allProductList)
        // this.isFinish = true
      }
    },
  },
  methods: {
    //获取商品橱窗数据
    findProduct(id){
      let productParam = {
        product:{
          video:{id},
        }
      }
      //获取短视频对应的商品数
      countByVideo(productParam,res => {
        this.originalListLength = res

        let param = {
          product:{video:{id}},
          pageable:{page: 1, size: this.originalListLength, sort: 'id', desc: true}
        }
        // console.log(param)
        findByVideo(param,data => {
          console.log(data)
          data.forEach(item => {
            item.id = item.id.toString()
            this.originalIdList.push(item.id)
            item.type = "link"
            delete item.amount
            delete item.salesQuantity
          })
          console.log(this.originalIdList)
          this.$store.commit('changeProductList',data.reverse())
          this.listUpdate()
          // 备份商品列表数据
          this.$store.commit('saveOldProductList',this.allProductList)
          // console.log(this.$store.state.oldProductList)
        })
      })
    },
    //更新商品橱窗列表
    listUpdate(){
      this.total = this.$store.state.addProductList.slice(0).length
      this.allProductList = this.$store.state.addProductList.slice(0)
      let list = this.allProductList.slice(0)
      for(let i=0;i<list.length;i++){
        //position和sellable属性已经赋值过的项不需要继续赋值
        if(!list[i].position && !list[i].sellable){
          list[i].position = i+1
          list[i].sellable = false
        }
      }

      let showList = this.getPageData(this.page,this.pageSize).slice(0)
      if(showList.length == 0){ //移除时可能会遇到最后一页只有一条数据的情况，在这里判断移除后该页是否还有数据，没有的展示上一页
        showList = this.getPageData(this.page-1,this.pageSize).slice(0)
      }
      this.data = showList.slice(0)
    },
    //分页后获取页对应数据
    getPageData(page,pageSize){
      let start = (page-1) * pageSize
      let end = page * pageSize
      let showList = this.allProductList.slice(start,end)
      return showList
    },
    //条件搜索
    searchBySearchItem(res){
      console.log(res)
      // this.isFirst = false
      this.page = 1
      let list = []
      if(res.title && res.type){
        this.disabled = true
        this.$store.state.oldProductList.forEach(item => {
          //判断商品类型、判断标题是否存在指定字符
          if(item.type == res.type && item.title.indexOf(res.title)!=-1){
            list.push(item)
          }
        })
      }else if(res.title && !res.type){
        this.disabled = true
        this.$store.state.oldProductList.forEach(item => {
          //判断标题是否存在指定字符
          if(item.title.indexOf(res.title)!=-1){
            list.push(item)
          }
        })
      }else if(!res.title && res.type){
        this.disabled = true
        this.$store.state.oldProductList.forEach(item => {
          //判断商品类型
          if(item.type == res.type){
            list.push(item)
          }
        })
      }else{
        list = this.$store.state.oldProductList.slice(0)
        this.disabled = false
        // this.isFirst = true
      }
      console.log(list)
      this.$store.commit('changeProductList',list)
      this.listUpdate()
    },
    //下架
    takeDown(position){
      this.$confirm('确定下架该商品吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }).then(() => {
        let list = this.allProductList.slice(0)
        for(let i=0;i<list.length;i++){
          if(i == position-1){
            list[i].sellable = false
          }
        }
        this.$store.commit('changeProductList',list)
        this.listUpdate()

        //修改备份数据
        let backupData = this.$store.state.oldProductList.slice(0)
        for(let i=0;i<backupData.length;i++){
          if(i == position-1){
            backupData[i].sellable = false
          }
        }
        this.$store.commit('saveOldProductList',backupData)

        this.$message({
          type: 'success',
          message: '下架成功'
        });
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //上架
    shelves(position){
      this.$confirm('确定上架该商品吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }).then(() => {
        let list = this.allProductList.slice(0)
        for(let i=0;i<list.length;i++){
          if(i == position-1){
            list[i].sellable = true
          }
        }
        this.$store.commit('changeProductList',list)
        this.listUpdate()

        //修改备份数据
        let backupData = this.$store.state.oldProductList.slice(0)
        for(let i=0;i<backupData.length;i++){
          if(i == position-1){
            backupData[i].sellable = true
          }
        }
        this.$store.commit('saveOldProductList',backupData)

        this.$message({
          type: 'success',
          message: '上架成功'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //移除
    remove(position){
      this.$confirm('确认移除该商品吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }).then(() => {
        let list = this.allProductList.slice(0)
        //移除商品数据
        for(let i=0; i<list.length ;i++){
          if(list[i].position == position){
            list.splice(i,1)
          }
        }
        //重新赋值position属性值
        if(list.length>0){
          for(let i=0;i<list.length;i++){
            list[i].position = i+1
          }
        }

        this.$store.commit('changeProductList',list)
        this.listUpdate()

        //修改备份的数据
        let backupData = this.$store.state.oldProductList.slice(0)
        //移除商品数据
        backupData.splice(position-1,1)
        //重新赋值position属性值
        if(backupData.length>0){
          for(let i=0;i<backupData.length;i++){
            backupData[i].position = i+1
          }
        }
        this.$store.commit('saveOldProductList',backupData)

        // console.log(this.data)
        this.$message({
          type: 'success',
          message: '移除成功'
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //下移
    down(position){
      let list = this.allProductList.slice(0)
      if(position<list.length) {
        //修改上下两组数据的排序值
        for (let i = 0; i < list.length; i++) {
          if (i == (position - 1)) {
            list[i].position = list[i].position + 1
            list[i + 1].position = list[i + 1].position - 1
          }
        }
        //根据排序值对不同行数据进行排序
        for (let i = 0; i < list.length; i++) {
          for (let j = i + 1; j < list.length; j++) {
            if (list[i].position > list[i + 1].position) {
              let temp = list[i]
              list[i] = list[i + 1]
              list[i + 1] = temp
            }
          }
        }
        this.$store.commit('changeProductList', list)
        this.$store.commit('saveOldProductList', list)

        this.listUpdate()
      }
    },
    //上移
    up(position){
      console.log(this.allProductList)
      let list = this.allProductList.slice(0)
      console.log(list)
      if(position>0){
        //修改上下两组数据的排序值
        for(let i=0;i<list.length;i++){
          if(i==(position-1)){
            list[i].position = list[i].position-1
            list[i-1].position = list[i-1].position+1
          }
        }
        console.log('触发')
        //根据排序值对不同行数据进行排序
        for(let i=0;i<list.length;i++){
          for(let j=i+1;j<list.length;j++){
            if(list[i].position > list[i+1].position){
              let temp = list[i]
              list[i] = list[i+1]
              list[i+1] = temp
            }
          }
        }
        this.$store.commit('changeProductList',list)
        this.$store.commit('saveOldProductList',list)

        this.listUpdate()
      }
    },
    //每页数据条数改变时触发
    handleSizeChange(val){
      this.pageSize = val
      this.listUpdate()
    },
    //页码改变时触发
    handleCurrentChange(val){
      this.page = val
      this.listUpdate()
    },
    //点击添加商品按钮
    addGoods(){
      this.isAdd = true
    },
    //关闭添加商品
    closeAdd(isUpdate){
      this.isAdd = false
      if(isUpdate){
        // this.isFirst = true
        this.listUpdate()
        this.$store.commit('saveOldProductList',this.allProductList)
        console.log(this.$store.state.oldProductList)
      }
    },
    // //请求修改数据库商品上架状态
    // setProductStatus(productList){
    //   //将上架的商品抽取出来
    //   let sellableIdList = []
    //   productList.forEach(item => {
    //     if(item.sellable){ //上架
    //       sellableIdList.push(item.id)
    //     }
    //   })
    //   console.log(sellableIdList)
    //   //判断是否有上架商品，没有的话不调用修改上架状态方法
    //   if(sellableIdList.length > 0){
    //     //修改商品上架状态
    //     let sellableParam = {
    //       sellable: true,
    //       idList: sellableIdList
    //     }
    //     console.log(sellableParam)
    //
    //     batchReverse(sellableParam,data => {
    //       if(data == '204'){
    //         console.log('触发')
    //         this.$message.success('修改商品成功')
    //         this.cancel()
    //       }
    //     })
    //   }else{
    //     this.$message.success('修改商品成功')
    //     this.cancel()
    //   }
    // },
    //提交
    submit(){
      this.disabledSubmit = true
      if(this.id){ //编辑
        let productList = this.$store.state.oldProductList.slice(0)
        console.log(productList)

        //如果视频初始没有绑定商品，则不进行删除操作直接添加商品
        if(this.originalListLength == 0){ //短视频原本没有绑定商品

          //添加商品
          productList.forEach(item => {
            item.video = {id:this.id}
          })
          let param = {productList}
          console.log(param)
          save(param,data => {
            console.log(data)
            if(data == '204'){
              console.log('触发1')
              this.$message.success('修改商品成功')
              this.cancel()
            }
          })

        }else{ //原本有绑定商品，先删除原有商品再重新添加商品

          //先删除全部原有的商品
          let removeProductParam = {idList:this.originalIdList}

          console.log(removeProductParam)
          batchDelete(removeProductParam,data=>{
            if(data == '204'){
              console.log('删除后结果')

              //如果商品列表没有数据了就不再进行添加
              if(productList.length > 0){
                //重新添加商品
                productList.forEach(item => {
                  item.video = {id:this.id}
                })
                let param = {productList}
                console.log(param)
                save(param,data => {
                  if(data == '204'){
                    // console.log('触发2')
                    this.$message.success('修改商品成功')
                    this.cancel()
                  }
                })
              }
            }
          })
        }

      }else{ //上传
        this.$store.commit('changeProductList',this.$store.state.oldProductList)
        this.cancel()
      }
    },
    //取消
    cancel(){
      this.$emit('close');
      this.isAdd = false
      this.disabled = false
      this.isFinish = false
      this.originalIdList = []
    },
  }
}
</script>

<style lang="less" scoped>
.picture{
  width: 50px;
  height:50px;
}

.pager-group{
  width:100%;
  margin: 20px 0;
}
</style>
